//
//  MetaPermissionController.m
//  iGSS
//
//  Copyright 2010 Electronic Business Systems Ltd.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "MetaPermissionController.h"
#import "FormattingUtilities.h"
#import "GSSCommunicator.h"
#import "GSSObject.h"

@implementation MetaPermissionController

- (NSInteger)numberOfRows {
    NSInteger count = [object.permissions count];
    return self.isEditing ? count + 2 : count;
}

- (UITableViewCell *)cellForRow:(NSInteger)row {
    static NSString *CellIdentifier = @"MetaPermissionCell";
    
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2
                                       reuseIdentifier:CellIdentifier] autorelease];
        cell.detailTextLabel.adjustsFontSizeToFitWidth = YES;
        cell.detailTextLabel.minimumFontSize = 11;
    }

    NSInteger count = [object.permissions count];
    if (row < count) {
        NSDictionary *permission = [object.permissions objectAtIndex:row];
        NSString *name = [permission objectForKey:@"user"];
        if (!name)
            name = [permission objectForKey:@"group"];
        
        NSString *r = [[permission objectForKey:@"read"] intValue] ? @"R" : @"";
        NSString *w = [[permission objectForKey:@"write"] intValue] ? @"W" : @"";
        NSString *m = [[permission objectForKey:@"modifyACL"] intValue] ? @"M" : @"";
        cell.textLabel.text = [NSString stringWithFormat:@"%@ %@ %@", r, w, m];
        cell.detailTextLabel.text = name;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.editingAccessoryType = UITableViewCellAccessoryNone;
    } else {
        cell.textLabel.text = nil;
        if (row == count)
            cell.detailTextLabel.text = LocalizedString(@"Add user");
        else
            cell.detailTextLabel.text = LocalizedString(@"Add group");
        
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        cell.editingAccessoryType = UITableViewCellAccessoryDisclosureIndicator;        
    }
    
    return cell;
}

- (NSString *)titleForHeader {
    if ([object.permissions count] || self.isEditing)
        return LocalizedString(@"Permissions");
    else
        return nil;
}

- (NSString *)titleForFooter {
    if (![object.permissions count])
        return nil;
    
    return [NSString stringWithFormat:
            @"R: %@\nW: %@\nM: %@",
            LocalizedString(@"Read"),
            LocalizedString(@"Write"),
            LocalizedString(@"Modify ACL")];
}

- (UITableViewCellEditingStyle)editingStyleForRow:(NSInteger)row {
    if (row < [object.permissions count])
        return UITableViewCellEditingStyleDelete;
    else
        return UITableViewCellEditingStyleInsert;
}

- (BOOL)shouldIndentWhileEditingRow:(NSInteger)row {
    return YES;
}

- (void)didSelectRow:(NSInteger)row {
    NSInteger count = [object.permissions count];
    if (!self.isEditing || row < count)
        return;
    
    EditPermissionUserController *editPermissionController;
    
    if (row == count) {
        editPermissionController = [[EditPermissionUserController alloc]
                                    initWithNibName:@"EditPermissionUserController" bundle:nil];
    } else {
        editPermissionController = [[EditPermissionGroupController alloc]
                                    initWithNibName:@"EditPermissionGroupController" bundle:nil];
    }
    
	editPermissionController.delegate = self;
	[self.navigationController pushViewController:editPermissionController animated:YES];
	[editPermissionController release];
}

- (void)commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRow:(NSInteger)row {
    NSArray *permissions = object.permissions;
    NSDictionary *permission = [permissions objectAtIndex:row];
    
    NSMutableArray *m = [NSMutableArray arrayWithArray:permissions];
    [m removeObject:permission];
    NSArray *newPermissions = [NSArray arrayWithArray:m];
    [[GSSCommunicator defaultCommunicator] setPermissions:newPermissions ofObject:object];
    object.permissions = newPermissions;
    [object save];
    
    [self.tableView reloadData];
}


//MARK: -
//MARK: EditPermissionDelegate

- (void)permissionAdded:(NSMutableDictionary *)permission {
    NSArray *permissions = object.permissions;    
    if (!permission || [permissions containsObject:permission])
        return;
    
    NSArray *newPermissions = [permissions arrayByAddingObject:permission];
    [[GSSCommunicator defaultCommunicator] setPermissions:newPermissions ofObject:object];
    object.permissions = newPermissions;
    [object save];    
}

@end
